package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 患者挂号日期业务处理
 */
public class PatientSubscribeActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private String departmentsId,departmentsName,loginUserId;

    //    Initialize ListView
    private ListView queryDoctorListView;

    private Button date1,date2,date3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_subscribe);
//        实例化
        dbOpenHelper = new DBOpenHelper(PatientSubscribeActivity.this, "db_kindheartedness", null, 1);
        //        提取出传递的参数
        final Intent intent2 = getIntent();
        final Bundle bundle = intent2.getExtras();
//        提取出科室Id和名称及登录ID
        departmentsId = bundle.getString("departmentsId");
        departmentsName = bundle.getString("departmentsName");
        loginUserId = bundle.getString("loginUserId");
//        获取标题控制权
        TextView departmentsNameText = findViewById(R.id.departmentsName);
        departmentsNameText.setText(departmentsName);
//        获取listView控制权
        queryDoctorListView = findViewById(R.id.queryDoctorListView);
//        获取就诊日期按钮控制权
        date1 = findViewById(R.id.date1);
        date1.setOnClickListener(this);
        date2 = findViewById(R.id.date2);
        date2.setOnClickListener(this);
        date3 = findViewById(R.id.date3);
        date3.setOnClickListener(this);
//        取出当前日期，并以此回显后三天
        String dateString = DateUtil.dateString(new Date(),"yyyy-MM-dd");
        String nextDay1 = DateUtil.getNextDay(dateString, 1);
        String nextDay2 = DateUtil.getNextDay(dateString, 2);
        String nextDay3 = DateUtil.getNextDay(dateString, 3);
        date1.setText(nextDay1);
        date2.setText(nextDay2);
        date3.setText(nextDay3);

//        获取ListView点击事件并进行处理
        queryDoctorListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //                获取选项中的HashMap对象
                HashMap<String, String> map = (HashMap<String, String>) queryDoctorListView.getItemAtPosition(position);
                String doctorId = map.get("doctorId");
                String registrationDate = map.get("registrationDate");
                Log.i("获取的医生ID为:",doctorId);
//                跳转到预约缴费页面
                intent = new Intent(PatientSubscribeActivity.this,PatientSaveSubscribeActivity.class);
//                当前选中的医生ID编号
                bundle.putString("doctorId",doctorId);
                bundle.putString("registrationDate",registrationDate);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.date1:
//                查询当前日期是否有就诊医生
                String date1ToStr = date1.getText().toString();
                findByDate(date1ToStr);
                break;
            case R.id.date2:
//                查询当前日期是否有就诊医生
                String date2ToStr = date2.getText().toString();
                findByDate(date2ToStr);
                break;
            case R.id.date3:
//                查询当前日期是否有就诊医生
                String date3ToStr = date3.getText().toString();
                findByDate(date3ToStr);
                break;
            default:
                break;
        }
    }

    /**
     * 查询当前日期的就诊医生并回显
     * @param date1ToStr 就诊日期
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void findByDate(String date1ToStr) {
//        获取当前年
        String dateYeahToStr = DateUtil.dateString(new Date(),"yyyy");
        date1ToStr = dateYeahToStr+"-"+date1ToStr;
//        打开数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        /**
         * 1、通过科室ID查询所有的相关医生ID
         * 2、通过医生ID和就诊日期查询对应的挂号记录
         *  2.1、提取出对应医生Id和费用
         *  2.2、通过医生Id查询医生名称、简介
         * 3、提取出相应数据，例如：医生名称、费用、简介
         * 4、将数据保存并进行回显
         */
//        =========== 1、=================
        Cursor queryDoctor = readableDatabase.query("doctor_details", null, "departments_id = ?", new String[]{departmentsId}, null, null, null);
        Set<String> doctorIdList = new HashSet<>(6);
        while (queryDoctor.moveToNext()) {
            String doctorId = queryDoctor.getString(0);
            doctorIdList.add(doctorId);
        }
        if (Objects.isNull(doctorIdList)) {
            toast = ToastUtil.toastHint(toast,PatientSubscribeActivity.this,"暂无医生就诊！");
            return;
        }
//        ==============  2、 ===============
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(6);
//        循环查询是否具有挂号记录
        for (String doctorId : doctorIdList) {
            Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "doctor_id = ? and registration_date = ?", new String[]{doctorId,date1ToStr}, null, null, null);
            while (queryRegistrationSetting.moveToNext()) {
                //        存储临时Map对象
                Map<String, Object> map = new HashMap<>(6);
                String doctorId2 = queryRegistrationSetting.getString(1);
                String registrationMoney = queryRegistrationSetting.getString(6);
//                封装就诊费用
                map.put("registrationMoney",registrationMoney);
//              通过医生Id查询姓名和简介
                Cursor queryDoctor2 = readableDatabase.query("doctor_details", null, "id = ?", new String[]{doctorId2}, null, null, null);
                while (queryDoctor2.moveToNext()) {
                    String doctorId3 = queryDoctor2.getString(0);
                    String doctorName = queryDoctor2.getString(1);
                    String doctorDescribe = queryDoctor2.getString(5);
                    map.put("doctorId",doctorId3);
                    map.put("registrationDate",date1ToStr);
                    map.put("doctorName",doctorName);
                    if (doctorDescribe != null) {
                        map.put("doctorDescribe",doctorDescribe);
                        resultList.add(map);
                        break;
                    }
                    map.put("doctorDescribe","暂无简介");
                    resultList.add(map);
                    break;
                }
                break;
            }
        }
        //        判断是否具有医生
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, PatientSubscribeActivity.this, "暂无医生就诊，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                PatientSubscribeActivity.this,
                resultList,
                R.layout.query_registration_doctor,
                new String[]{
                        "doctorName","doctorId","registrationDate",
                        "registrationMoney", "doctorDescribe",
                },
                new int[]{
                        R.id.doctorName,R.id.doctorId,R.id.registrationDate,
                        R.id.registrationMoney, R.id.doctorDesc,
                }
        );
        queryDoctorListView.setAdapter(simpleAdapter);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}